package com.example.demo.core.resolver;

import com.example.demo.core.annotations.ApiAuthUserId;
import com.example.demo.core.exception.ProgramException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Optional;

/**
 * @author yj
 * @date 2021-07-24 21:51
 */
@Slf4j
@Component
public class ApiAuthUserIdResolver implements HandlerMethodArgumentResolver {

    /**
     * 判断方法内参数是否存在
     *
     * @param methodParameter 方法
     * @return true 存在且不为空  | false 不存在或者为空
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotations() && methodParameter.hasParameterAnnotation(ApiAuthUserId.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        ApiAuthUserId apiAuthUserId = Optional
                .ofNullable(methodParameter.getParameterAnnotation(ApiAuthUserId.class))
                .orElseThrow(() -> new ProgramException("缺少必要参数"));
        return Optional.
                ofNullable(nativeWebRequest.getAttribute("userId", RequestAttributes.SCOPE_REQUEST)).
                orElse("");

    }
}
